// 渲染数据
const getStudentsMessage = async () => {
  const { data } = await get("/students");
  // console.log(data);
  const studentsHTML = data
    .map(
      (item) => `
<tr>
<td>${item.name}</td>
<td>${item.age}</td>
<td>${item.gender ? "男" : "女"}</td>
<td>第${item.group}组</td>
<td>${item.hope_salary}</td>
<td>${item.salary}</td>
<td>${item.province + item.city + item.area}</td>
<td>
  <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen" data-id="${
    item.id
  }"></i></a>
  <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id="${
    item.id
  }"></i></a>
</td>
</tr>
`
    )
    .join("");
  document.querySelector(".list").innerHTML = studentsHTML;
  document.querySelector(".total").innerHTML = data.length;
};
// 进入页面调用渲染学生列表函数
getStudentsMessage();
// 初始化模态框 & 城市选择
// bootstrap的模态框直接cv即可
const modalBox = document.querySelector("#modal");
const modal = new bootstrap.Modal(modalBox);
// 省份
const ps = document.querySelector("[name=province]");
const cs = document.querySelector("[name=city]");
const as = document.querySelector("[name=area]");
const form = document.querySelector("#form");
// 让模态框显示
// modal.show();
// 2.获取模态框里的数据到真实的dom中
// 封装请求省市数据的函数
const initCity = async () => {
    const provinceRes = await get('/api/province')

    // console.log(provinceRes);

    const provinceHTML = provinceRes.data.map(item => `<option value="${item}">--${item}--</option>`).join('')

    ps.innerHTML = '<option value="北京">--省份--</option>' + provinceHTML

    ps.addEventListener('change', async function () {
      cs.value = ''
      renderCity(ps.value)

      cs.addEventListener('change', async function () {
        as.value = ''
        renderArea(ps.value, cs.value)
      })
    })
  }

  initCity()

  const renderCity = async (pname) => {
    const cityRes = await get('/api/city', { pname })

    const cityHTML = cityRes.data.map(item => `<option value="${item}">--${item}--</option>`).join('')

    cs.innerHTML = '<option value="北京">--城市--</option>' + cityHTML
  }

  const renderArea = async (pname, cname) => {

    const areaRes = await get('/api/area', { pname, cname })

    const areaHTML = areaRes.data.map(item => `<option value="${item}">--${item}--</option>`).join('')

    as.innerHTML = '<option value="丰台区">--地区--</option>' + areaHTML
  }

// 3点击添加按钮显示modal层

document.querySelector("#openModal").addEventListener("click", function () {
  form.reset();
  modalBox.dataset.id = "add";
  // 弹框出现
  modal.show();
});
// 4给确定按钮绑定点击事件，新增和修改，通过自定义属性判断
document.querySelector("#submit").addEventListener("click", async () => {
  const data = serialize(form, { hash: true });
  data.age = +data.age;
  data.hope_salary = +data.hope_salary;
  data.salary = +data.salary;
  data.gender = +data.gender;
  data.group = +data.group;
  if (modalBox.dataset.id === "add") {
    try {
      await post("/students/", data);
      // 弹框隐藏
      modal.hide();
      alert("添加成功");
      getStudentsMessage()
    } catch (error) {
      alert("添加失败");
    }
  }else{
//     console.log(data);
//     console.log(modalBox.dataset.id);
// console.log('我要修改');
try{
    const res=await axios({method:'put',url:'/students/'+modalBox.dataset.id,data})

modal.hide()
alert('修改成功')
getStudentsMessage();
}
catch(error){
    alert('修改失败')
}
  }
});
// 5事件委托，绑定删除新增事件
document.querySelector(".list").addEventListener("click", async function (e) {
    const btn = e.target
  if (btn.classList.contains("bi-pen")) {
    // console.log("我是编辑");
//       // 弹框出现
  modal.show();

const {data}=await get('/students/'+btn.dataset.id)

document.querySelector('[name=name').value = data.name
document.querySelector('[name=age').value =data.age
document.querySelector('[name=group').value = data.group
document.querySelector('[name=hope_salary').value =data.hope_salary
document.querySelector('[name=salary').value = data.salary
// 区别性别2
data.gender
?document.querySelector('#cb01').checked = true
:document.querySelector('#cb02').checked = true
//   获取对应的省份的城市列表
// const cityRes=await get("/api/city", { pname: data.value });
// const cityHTML =cityRes.data
//       .map((item) => `  <option value="${item}">--${item}--</option>`)
//       .join("");
//     cs.innerHTML = `<option value="">--城市--</option>` + cityHTML;
//     document.querySelector('[name=city').value=data.city;
//     // 获取城市
//     const areaRes=await get('/api/area',{ pname: data.province,
//         cname: data.city,})
//    const areaHTML =areaRes.data.map((item) => `  <option value="${item}">--${item}--</option>`) .join("");
//   as.innerHTML = `<option value="">--地区--</option>` + areaHTML;
//   document.querySelector('[name=area').value=data.area;

ps.value = data.province

await renderCity(ps.value)

cs.value =data.city

await renderArea(ps.value, cs.value)

as.value = data.area


  modalBox.dataset.id=btn.dataset.id
modal.show();
  } else if (btn.classList.contains('bi-trash')) {
    console.log(btn.dataset.id);
    try {
      await axios({ method: 'DELETE', url: '/students/' + btn.dataset.id })
      getStudentsMessage()
      alert('删除成功')
    } catch (error) {
      alert('删除失败')
    }
  }
});
